from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.core.mail import send_mail
from django.conf import settings
from django.contrib.auth import authenticate
from rest_framework_simplejwt.tokens import RefreshToken
import json
import random
import logging
from . import models
from .models import Users, EmailVerificationCode, Favor, FavorItinerary
from rest_framework_simplejwt.views import TokenObtainPairView
from .serializers import MyTokenObtainPairSerializer
from django.utils import timezone
from django.forms.models import model_to_dict
# 注册用户
import datetime
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.hashers import make_password, check_password
from rest_framework import views
from django.forms.models import model_to_dict
from flight.models import Itinerary
import jwt
from jwt.exceptions import ExpiredSignatureError, InvalidTokenError



# 访问注册页面时创建会话键
@csrf_exempt
def get_session_key(request):
    print(request)
    if not request.session.session_key:
        request.session.create()
    print(request.session.session_key)

    return JsonResponse({'session_key': request.session.session_key})


# 注册用户
@csrf_exempt
def create_user(request):
    res = {"status": 400, "message": "", "data": None}
    if request.method == "POST":
        try:
            data = json.loads(request.body)
            # 从解析的数据中获取'signUpForm'和'session_key'
            session_key = data.get('session_key', None)
            print(session_key)
            # 判断验证码是否正确
            code = EmailVerificationCode.objects.filter(session_key=session_key).first()
            if code:
                print(f"Code found: {code.captcha}")
            else:
                print("No code found with the given session key.")
            data.pop('session_key', None)
            print(data)
            if code.captcha == data['signUpForm']['verificationCode']:
                data['signUpForm'].pop('verificationCode', None)
            else:
                res["status"] = 400
                res["message"] = "验证码不正确"
                return JsonResponse(res)
                # 将 mail 字段改为 email
            signUpForm = data['signUpForm']
            if 'mail' in signUpForm:
                signUpForm['email'] = signUpForm.pop('mail')

            # 确保传入的数据包含必要的字段
            required_fields = ['username', 'email', 'password']
            for field in required_fields:
                if field not in signUpForm:
                    raise ValueError(f"缺少必要字段: {field}")
            is_exist = Users.objects.filter(username=signUpForm['username']).exists()
            if  is_exist:
                return JsonResponse({"status": 400, "message": "用户已存在"})
            else:
                # 创建一个 User 对象
                user = Users.objects.create(
                    username=signUpForm['username'],
                    password=make_password(signUpForm['password']),  # 加密密码
                    email=signUpForm['email']
                )
                user.save()

                res["status"] = 200
                res["message"] = "用户创建成功"
                res["data"] = {
                    "username": user.username,
                    "email": user.email,
                }
        except ValueError as ve:
            res["status"] = 400
            res["message"] = str(ve)
        except Exception as e:
            res["status"] = 500
            res["message"] = "验证码不正确 "
    else:
        res["message"] = "请使用POST方法"
    return JsonResponse(res)


# 发送验证码
@csrf_exempt
def verification_code(request):
    if request.method == 'POST':
        print("normal run")
        try:
            data = json.loads(request.body)
            print(data)
            email = data['email']
            # 获取会话键
            session_key = data['session_key']
            print(f"获得邮件{email}")
            if not email:
                return JsonResponse({'status': 400, 'message': 'Email is required'})
            print(f"Email: {email},{session_key}")  # 打印 email
            code = str(random.randint(100000, 999999))  # 生成六位验证码
            print(f"Generated code: {code}")  # 打印生成的验证码
            request.session['verification'] = code
            print(f"Session code: {request.session['verification']}")  # 打印会话中的验证码
            print(f", send_time={timezone.now()}")

            send_mail(
                '机票价格预测系统验证码',
                f'您的注册验证码是 {code}',
                settings.EMAIL_HOST_USER,
                [email],
            )
            verification = models.EmailVerificationCode.objects.create(
                captcha=code,
                send_time=timezone.now(),
                session_key=session_key
            )
            verification.save()
            print("邮箱发送成功")
            # 保存验证码到数据库或缓存 后续验证
            return JsonResponse({'status': 200, 'message': '验证码已发送'})
        except Exception as e:
            return JsonResponse({'status': 500, 'message': str(e)})
    else:
        return JsonResponse({'status': '400', 'message': '无效请求'})


@csrf_exempt
# 用户信息返回
def personal(request):
    if request.method == 'GET':
        return JsonResponse(request)


# 用户登录
@csrf_exempt
def user_login(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            print(data)
            username = data['username']
            password = data['password']
            user = Users.objects.filter(username=username).first()
            print(password)
            if user and check_password(password, user.password):
                print(user.password)
                # 生成 JWT
                refresh = RefreshToken.for_user(user)
                # 手动设置 token 中的用户信息
                access_token = str(refresh.access_token)
                refresh_token = str(refresh)

                return JsonResponse({
                    'status': 200,
                    'message': 'Login successful',
                    'data': {
                        'access_token': access_token,
                        'refresh_token': refresh_token,
                        'user': {
                            'username': username,
                        }
                    }
                })
            else:
                return JsonResponse({'status': 400, 'message': '用户名或密码错误'})
        except Exception as e:
            return JsonResponse({'status': 500, 'message': str(e)})
    return JsonResponse({'status': 400, 'message': '无效请求'})


@csrf_exempt
def user_login_test(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            username = data['username']
            password = data['password']
            user = authenticate(request, username=username, password=password)

            if user is not None:
                login(request, user)
                token, created = Token.objects.get_or_create(user=user)
                print(token.key)
                return JsonResponse({"status": 200,
                                     "message": 'Login successful',
                                     "data": {
                                         'token': token.key,
                                         "user": {
                                             "username": username,
                                         }
                                     }
                                     })
            else:
                print("not good")
                return JsonResponse({'status': 400, 'message': '用户名或密码错误'})
        except Exception as e:
            print("No")
            print(str(e))
            return JsonResponse({'status': 500, 'message': str(e)})
    return JsonResponse({'status': 400, 'message': '无效请求'})


# 检查用户
@csrf_exempt
def check_user(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            username = data['userId']
            print(username)
            user = Users.objects.filter(username=username).first()
            user_dict = model_to_dict(user)
            print(user)
            print(user_dict)
            if Users.objects.filter(username=username):
                print("normal run")
                return JsonResponse({'status': 200,
                                     "user": {
                                         "userId": username,
                                         "password": user.password,
                                         "email": user.email,
                                     }
                                     })
            else:
                return JsonResponse({'status': 404, 'message': '用户不存在'})
        except Exception as e:
            print(str(e))
            return JsonResponse({'status': 500, 'message': str(e)})
    return JsonResponse({'status': 400, 'message': '无效请求'})


# 修改用户信息
@csrf_exempt
def modify_user(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            print(data)
            username = data['oldUserId']
            user = Users.objects.get(username=username)
            if data.get('newUserId'):
                new_username = data['newUserId']
                user.username=new_username
            if data.get('newEmail'):
                new_email = data['newEmail']
                user.email = new_email
            if data.get('newPassword'):
                new_password = data['newPassword']
                user.password = new_password
            user.save()
            return JsonResponse({
                "status": 200,
                "data":{
                    "user": {
                        "userId": user.username,
                        "email": user.email,
                        "password": user.password,
                    },
                "message": 'ChangePersonalInfo successful',
                }
            })
        except Users.DoesNotExist:
            return JsonResponse({'status': 404, 'message': '用户不存在'})
        except Exception as e:
            return JsonResponse({'status': 500, 'message': str(e)})
    return JsonResponse({'status': 400, 'message': '无效请求'})


# 修改密码
@csrf_exempt
def change_password(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            username = data['username']
            old_password = data['old_password']
            new_password = data['new_password']
            email = data['email']
            code = data[code]  # 新增的验证码字段
            # 验证旧密码
            user = authenticate(username=username, password=old_password)
            if user is not None:
                session_code = request.session.get('verification_code')
                if session_code != code:
                    return JsonResponse({'status': 400, 'message': '验证码错误'})
                # 更新密码
                user.set_password(new_password)
                user.save()
                return JsonResponse({'status': 200, 'message': '密码修改成功'})
            else:
                return JsonResponse({'status': 400, 'message': '旧密码不正确'})
        except Exception as e:
            return JsonResponse({'status': 500, 'message': str(e)})
    return JsonResponse({'status': 400, 'message': '无效请求'})


# 修改邮箱  直接根据密码修改绑定
@csrf_exempt
def change_email(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            username = data['username']
            password = data['password']
            new_email = data['new_email']
            user = authenticate(username=username, password=old_email)
            if user is not None:
                user.email = new_email
                user.save()
                return JsonResponse({'status': 200, 'message': '邮箱修改成功'})
            else:
                return JsonResponse({'status': 400, 'message': '邮箱修改失败'})
        except Exception as e:
            return JsonResponse({'status': 500, 'message': str(e)})
    return JsonResponse({'status': 400, 'message': '无效请求'})


# 修改密码
@csrf_exempt
def change_password(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            username = data['username']
            old_password = data['old_password']
            new_password = data['new_password']
            email = data['email']
            code = data[code]  # 新增的验证码字段
            # 验证旧密码
            user = authenticate(username=username, password=old_password)
            if user is not None:
                session_code = request.session.get('verification_code')
                if session_code != code:
                    return JsonResponse({'status': 400, 'message': '验证码错误'})
                # 更新密码
                user.set_password(new_password)
                user.save()
                return JsonResponse({'status': 200, 'message': '密码修改成功'})
            else:
                return JsonResponse({'status': 400, 'message': '旧密码不正确'})
        except Exception as e:
            return JsonResponse({'status': 500, 'message': str(e)})
    return JsonResponse({'status': 400, 'message': '无效请求'})


# 根据航班信息  输入框、进行粗略查询以及精细查询
@csrf_exempt
def rough_query(request):
    if request.method == 'POST':
        pass


@csrf_exempt
def fine_query(request):
    if request.method == 'POST':
        pass



@csrf_exempt
def collect(request):
    try:
        auth_header = request.headers.get('Authorization')
        token_str = auth_header.split(' ')[1]
        payload = jwt.decode(token_str, settings.SECRET_KEY, algorithms=['HS256'])
        user_id = payload['user_id']

        # 获取用户及其对应的收藏夹信息
        favors = Favor.objects.filter(user_id=user_id)
        favor_itineraries = FavorItinerary.objects.filter(favor__in=favors).select_related('itinerary')

        favor_list = []
        for fav_itinerary in favor_itineraries:
            flight = fav_itinerary.itinerary
            fav_data = {
                'uid': flight.itinerary_id,
                'departure_city': flight.departure_city,
                'departure_airport': flight.departure_airport,
                'arrival_city': flight.arrival_city,
                'arrival_airport': flight.arrival_airport,
                'startDate': flight.departure_date,
                'duration': flight.departure_time,
                'arrival_time': flight.arrival_time,
                'price': flight.price,
                'airline': flight.airline,
                'airlineNum': flight.flight_no,
                'route': flight.departure_city+'-'+flight.arrival_city,
            }
            favor_list.append(fav_data)

        return JsonResponse({"data": favor_list}, status=200)

    except Exception as e:
        return JsonResponse({'error': str(e)}, status=500)


# 收藏航班
@csrf_exempt
def save_personal(request):
    try:
        data = json.loads(request.body)
        uid = data.get('uid')
        username = data.get('userId')

        user = Users.objects.get(username=username)
        favor, created = Favor.objects.get_or_create(user=user)
        itinerary = Itinerary.objects.get(itinerary_id=uid)
        print(itinerary)
        FavorItinerary.objects.create(favor=favor, itinerary=itinerary)

        return JsonResponse({'status': 200, 'message': 'Saved successfully'})
    except Exception as e:
        return JsonResponse({'status': 500, 'message': str(e)})


# 删除航班
@csrf_exempt
def delete_personal(request):
    try:
        data = json.loads(request.body)
        uid = data.get('uid')
        username = data.get('userId')
        print(username)

        user = Users.objects.get(username=username)
        favor = Favor.objects.get(user=user)
        itinerary = Itinerary.objects.get(itinerary_id=uid)
        print(itinerary)
        favor_itinerary = FavorItinerary.objects.get(favor=favor, itinerary=itinerary)
        print(favor_itinerary)
        favor_itinerary.delete()

        return JsonResponse({'status': 200, 'message': 'Deleted successfully'})
    except Exception as e:
        return JsonResponse({'status': 500, 'message': str(e)})
